import "./index.css";
import * as React from "react";
import SessionStorageKey from "../../enum/SessionStorageKey";
import Link from "react-router-dom/es/Link";
import DialogBuilder from "../../utils/DialogBuilder";
import PropTypes from "prop-types";

/**
 * 侧边菜单栏
 */
export default class Sidebar extends React.Component {
    static contextTypes = {
        router: PropTypes.object
    };

    componentWillMount() {
        //获取菜单和用户数据
        try{
            this.setState({
                menuList: JSON.parse(sessionStorage.getItem(SessionStorageKey.menuList)),
                userInfo: JSON.parse(sessionStorage.getItem(SessionStorageKey.userInfo))
            }, ()=>{
                if(!this.state.menuList || !this.state.userInfo){
                    this.context.router.history.replace("/login");
                    return ;
                }
                const currentPath = this.context.router.history.location.pathname;
                for(let menu of this.state.menuList){
                    if(currentPath.startsWith(menu.url)){
                        menu.expanded = true;
                        for(let child of menu.children){
                            if(currentPath.startsWith(child.url)){
                                child.active = true;
                                break;
                            }
                        }
                        break;
                    }
                }
                this.setState(this.state);
            });
        }catch (e) {
            console.error(e);
            new DialogBuilder("需要重新登录，点击继续!")
                .btn("继续", ()=>this.context.router.history.replace("/login"))
                .removeOnClose();
        }
    }

    /**
     * 菜单的展开和收起
     * @param index
     */
    onMenuExpandHandler(index){
        let menu = this.state.menuList[index];
        menu.expanded = !menu.expanded;
        this.setState(this.state);
        if(menu.expanded){
            menu.childrenElement.style.height = menu.childrenElement.scrollHeight + "px";
        }else{
            menu.childrenElement.style.height = null;
        }
    }

    /**
     * 菜单项被点击事件
     */
    onMenuItemClickHandler(menuIndex, childIndex){
        let state = this.state;
        state.menuList.forEach((menu, index)=>{
            if(menuIndex === index){
                menu.expanded = true;
                menu.children.forEach((child, index)=>{
                    child.active = childIndex === index;
                })
            }else{
                menu.expanded = false;
                menu.children.forEach(child=>child.active = false);
            }
        });
        this.setState(state);
    }

    render() {
        if(!this.state.menuList || !this.state.userInfo) return '';
        //渲染数据
        return (
            <div id="sidebar" className="border-right">
                <div id="userCard" className="text-center mt-2">
                    <div id="headImageBox" className="mb-2">
                        <img className="rounded" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%3E%3Crect%20width=%22100%25%22%20height=%22100%25%22%20style=%22fill:#c6c6c6%22%3E%3C/rect%3E%3C/svg%3E" alt=""/>
                    </div>
                    <h3>{this.state.userInfo.nickname}</h3>
                </div>
                <div id="menuList" className="border-top">
                    <ul>
                        {this.state.menuList.map((item, menuIndex)=>{
                            if(item.children.length){
                                return <li key={menuIndex} className={"expansible" + (item.expanded?" expanded":"")}>
                                    <span className="title" onClick={this.onMenuExpandHandler.bind(this, menuIndex)}>{item.name}</span>
                                    <ul ref={element=>(item.childrenElement=element) && item.expanded && (element.style.height=element.scrollHeight+"px")}>
                                        {item.children.map((child,childIndex)=>
                                            <li
                                                key={childIndex}
                                                className={child.active?"active":""}
                                                onClick={this.onMenuItemClickHandler.bind(this, menuIndex, childIndex)}
                                            >
                                                <Link className="title" replace={true} to={child.url}>{child.name}</Link>
                                            </li>
                                        )}
                                    </ul>
                                </li>
                            }else{
                                return <li key={menuIndex} className={item.active?"active":""}><Link className="title" replace={true} to={item.url}>{item.name}</Link></li>
                            }
                        })}
                    </ul>
                </div>
            </div>
        )
    }
}
